from flask import jsonify, make_response, request, g
from flask_restful import Resource
from sqlalchemy import func

from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from apps.settingApi.switchCase.serializeParameter import getArgsData

from apps.settingApi.switchCase.settingCurd import getList, postList, getPk, deletePk, putPk
from apps.settingApi.api.role.model import roleModel, rolePermissionModel,roleUserModel
from apps.settingApi.api.funs.model import funsModel
from apps.settingApi.api.users.model import permissionModel
from apps.settingApi.api.lessees.model import lesseesFunsModel
from apps.settingApi.api.users.model import usersModel
from comm.sqlalchemyConfig import db
from comm.decorator import login_required

roleViewModel = roleModel
rolePermissionViewModel = rolePermissionModel
permissionViewModel = permissionModel
lesseesFunsViewModel = lesseesFunsModel
roleUserViewModel = roleUserModel
funsViewModel = funsModel
usersViewModel = usersModel
# 字典操作=========================================================
class roleListView(Resource):
    # 查询用户列表
    @login_required()
    def get(self):
        # 获取所有的参数
        args = request.args
        objData ,err = getList(roleViewModel,args)
        if err!=None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功','result': objData}), 200)
    @login_required()
    def post(self):
        # 获取所有参数
        if request.is_json == True:
            args = request.get_json()
        else:
            args = request.form
        if len(args) == 0:
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        args['lessees_id'] = g.lessees_id
        objData,err = postList(roleViewModel,args)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

class rolePkView(Resource):
    @login_required()
    def get(self, pk):
        objData, err = getPk(roleViewModel, pk)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def put(self, pk):
        # 获取所有参数
        if request.is_json == True:
            args = request.get_json()
        else:
            args = request.form
        if len(args) == 0:
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        objData, err = putPk(roleViewModel, pk, args)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def delete(self, pk):
        objData, err = deletePk(roleViewModel, pk)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)


class rolePermissionListView(Resource):
    # 查询用户列表
    @login_required()
    def get(self):
        # 获取所有的参数
        args = request.args
        lessees_id = g.lessees_id
        if g.lessees_type==1:
            lessees_id_z = args.get('lessees_id', None)
            if lessees_id_z != None:
                lessees_id = lessees_id_z
        role_id = args.get('role_id', None)
        if role_id is None or role_id=='':
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        funsFiledList = [
        funsViewModel.status == 1,func.coalesce(funsViewModel.parent_code,'')=='']
        if  g.lessees_type !=1:
            funsFiledList.append(lesseesFunsViewModel.lessees_id == lessees_id)
            funsFiledList.append(funsViewModel.code == lesseesFunsModel.funs_code)
        # 获取租户的模块，一级菜单
        funsList = db.session.query(funsViewModel).filter(*funsFiledList).order_by(funsViewModel.sort.desc()).all()
        dataList = []
        # 默认展开的节点
        print(funsList)
        defaultExpandedKeys = []
        for itm in funsList:
            itm_z = {}
            itm_z['id'] = itm.id
            itm_z['label'] = itm.name
            itm_z['status'] = itm.status
            itm_z['code'] = itm.code
            itm_z['children'] = []
            defaultExpandedKeys.append(itm.code)
            # 获取租户的模块，一级菜单权限
            permission = permissionViewModel.query.filter(permissionViewModel.funs_code == itm.code).order_by(
                permissionViewModel.name.desc()).all()
            for itm3 in permission:
                permissionObj = {}
                permissionObj['id'] = itm3.id
                permissionObj['label'] = itm3.name
                permissionObj['status'] = itm3.status
                permissionObj['code'] = itm3.code
                permissionObj['children'] = []
                itm_z['children'].append(permissionObj)
            # 获取租户的模块，二级菜单权限
            funsListChildren = db.session.query(funsViewModel).filter(funsViewModel.parent_code==itm.code).order_by(funsViewModel.sort.desc()).all()
            for itm2 in funsListChildren:
                funsListChildrenObj = {}
                funsListChildrenObj['id'] = itm2.id
                funsListChildrenObj['label'] = itm2.name
                funsListChildrenObj['status'] = itm2.status
                funsListChildrenObj['code'] = itm2.code
                funsListChildrenObj['children'] = []
                itm_z['children'].append(funsListChildrenObj)
                # defaultExpandedKeys.append(itm2.code)
                permission = permissionViewModel.query.filter(permissionViewModel.funs_code == itm2.code).order_by(permissionViewModel.name.desc()).all()
                for itm3 in permission:
                    permissionObj = {}
                    permissionObj['id'] = itm3.id
                    permissionObj['label'] = itm3.name
                    permissionObj['status'] = itm3.status
                    permissionObj['code'] = itm3.code
                    permissionObj['children'] = []
                    funsListChildrenObj['children'].append(permissionObj)
            dataList.append(itm_z)
        # 获取所有的权限
        rolePermission = rolePermissionViewModel.query.filter(rolePermissionViewModel.lessees_id==lessees_id,rolePermissionViewModel.role_id==role_id)
        rolePermissionList = list(map(lambda x:x.permission_code,rolePermission))
        data = {
            "data":dataList,
            "checkedKeys":rolePermissionList,
            "defaultExpandedKeys":defaultExpandedKeys
        }

        return make_response(jsonify({'msg': '成功','result': data}), 200)
    @login_required()
    def post(self):
        # 获取参数
        args, err = getArgsData()
        if err != None:
            return make_response(jsonify({'msg': err, }), 202)
        lessees_id = g.lessees_id
        if g.lessees_type == 1:
            lessees_id_z = args.get('lessees_id', None)
            if lessees_id_z != None:
                lessees_id = lessees_id_z
        role_id = args.get('role_id', None)
        if role_id is None or role_id == '':
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        checkedKeys = args.get('checkedKeys', None)
        if checkedKeys is None or checkedKeys == '':
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        db.session.query(rolePermissionViewModel).filter(rolePermissionViewModel.lessees_id == lessees_id,rolePermissionViewModel.role_id==role_id).delete()
        addList = []
        # 过滤掉多余的节点只保留根节点
        checkedKeysFilter = db.session().query(permissionViewModel).filter(permissionViewModel.code.in_(checkedKeys))
        for itm in checkedKeysFilter:
            itm_z = {}
            itm_z['id'] = caseGetPrimaryKeyData()
            itm_z['permission_code'] = itm.code
            itm_z['lessees_id'] = lessees_id
            itm_z['role_id'] = role_id
            addList.append(rolePermissionViewModel(**itm_z))
        if len(addList) > 0:
            db.session.add_all(addList)
        db.session.commit()
        return make_response(jsonify({'msg': '成功', 'result': []}), 200)

class roleUserListView(Resource):
    # 查询用户列表
    @login_required()
    def get(self):
        # 获取所有的参数
        args = request.args
        lessees_id = g.lessees_id
        if g.lessees_type==1:
            lessees_id_z = args.get('lessees_id', None)
            if lessees_id_z != None:
                lessees_id = lessees_id_z
        role_id = args.get('role_id', None)
        if role_id is None or role_id=='':
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        # 获取租户的所有用户
        userList = db.session.query(usersViewModel).filter(usersViewModel.lessees_id == lessees_id).order_by(
                usersViewModel.id.desc()).all()
        dataList = []
        for itm in userList:
            itm_z = {}
            itm_z['id'] = itm.id
            itm_z['label'] = itm.username
            dataList.append(itm_z)
        # 获取角色所有的用户
        roleUser = roleUserModel.query.filter(roleUserModel.lessees_id == lessees_id,roleUserModel.role_id == role_id).all()

        roleUserList = list(map(lambda x:x.user_id,roleUser))
        data = {
            "data":dataList,
            "checkedKeys":roleUserList
        }

        return make_response(jsonify({'msg': '成功','result': data}), 200)
    @login_required()
    def post(self):
        # 获取参数
        args, err = getArgsData()
        if err != None:
            return make_response(jsonify({'msg': err, }), 202)

        lessees_id = g.lessees_id
        if g.lessees_type == 1:
            lessees_id_z = args.get('lessees_id', None)
            if lessees_id_z != None:
                lessees_id = lessees_id_z
        role_id = args.get('role_id', None)
        if role_id is None or role_id == '':
            return make_response(jsonify({'msg': '参数不能为空1'}), 202)
        checkedKeys = args.get('checkedKeys', None)
        if checkedKeys is None or checkedKeys == '':
            return make_response(jsonify({'msg': '参数不能为空2'}), 202)
        db.session.query(roleUserModel).filter(roleUserModel.lessees_id == lessees_id,roleUserModel.role_id==role_id).delete()
        addList = []
        for itm in checkedKeys:
            itm_z = {}
            itm_z['id'] = caseGetPrimaryKeyData()
            itm_z['user_id'] = itm
            itm_z['lessees_id'] = lessees_id
            itm_z['role_id'] = role_id
            addList.append(roleUserModel(**itm_z))
        if len(addList) > 0:
            db.session.add_all(addList)
        db.session.commit()

        return make_response(jsonify({'msg': '成功', 'result': []}), 200)

